package com.dance.netty.netty.protobuf;

import com.dance.netty.netty.protobuf.pojo.StudentPOJO;
import com.dance.netty.netty.protobuf.proto.MyDataInfo;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
public class NettyServerHandler extends SimpleChannelInboundHandler< MyDataInfo.MyMessage> {
//public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,  MyDataInfo.MyMessage msg) throws Exception {
//        System.out.println("客户端发送的数据:" + msg.getId() + " " + msg.getName());
        if(msg.getDataType() == MyDataInfo.MyMessage.DataType.StudentType){
            System.out.println("客户端发送的数据:" + msg.getStudent().getId() + " " + msg.getStudent().getName());
        }else if(msg.getDataType() == MyDataInfo.MyMessage.DataType.WorkerType){
            System.out.println("客户端发送的数据:" + msg.getWorker().getId() + " " + msg.getWorker().getName());
        }
    }

//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        // 读取从客户端发送的额StudentPOJO.student
//        StudentPOJO.Student student = (StudentPOJO.Student) msg;
//        System.out.println("客户端发送的数据:" + student.getId() + " " + student.getName());
//    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 客户端", StandardCharsets.UTF_8));
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}
